package com.itheima.reggie.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * 按照MP框架规范自定义元数据对象处理器，统一完成公共字段自动填充
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入数据时自动填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("插入数据时自动填充...");

        //获取当前登录员工id
        Long currentId = BaseContext.getCurrentId();

        metaObject.setValue("updateTime",LocalDateTime.now());
        metaObject.setValue("createTime",LocalDateTime.now());
        metaObject.setValue("updateUser",currentId);
        metaObject.setValue("createUser",currentId);
    }

    /**
     * 修改数据时自动填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpSession session = requestAttributes.getRequest().getSession();
        Long empId = (Long) session.getAttribute("employee");

        //获取当前登录员工id
        Long currentId = BaseContext.getCurrentId();

        //获得当前线程的id
        long id = Thread.currentThread().getId();
        log.info("线程id为：{}",id);

        log.info("修改数据时自动填充...");
        //为公共字段赋值，参数一：属性名 参数二：设置的值
        metaObject.setValue("updateTime",LocalDateTime.now());
        metaObject.setValue("updateUser",currentId);
    }
}
